package com.lx.blogflux.web;

import com.lx.blogflux.dao.ArticleDao;
import com.lx.blogflux.entity.Article;
import com.lx.blogflux.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("article")
public class ArticleDo {
    @Autowired
    ArticleDao articleDao;

    @RequestMapping("query")
    public Mono<?> query(Article article,
                         @RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "10") int size) {
        // 构建查询条件
        ExampleMatcher matcher = ExampleMatcher.matching();
        if (!Utils.isEmpty(article.getTitle())) {
            // 模糊查询
            matcher = matcher.withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains());
        }
        Example example = Example.of(article, matcher);
        return articleDao
                // 查询当前页数据
                .findAll(example)
                .skip((page - 1) * size)
                .take(size)
                // 将 flux 转为 mono
                .collectList()
                // 查询总行数 => 组合成 map 集合
                .zipWith(articleDao.count(example),
                        (a, b) -> Utils.asMap("records", a, "total", b));
    }

    @RequestMapping("queryTitle")
    Flux<Article> queryTitle(String title) {
        return articleDao.findByTitle(title);
    }

    @RequestMapping("queryLikeTitle")
    Flux<Article> queryLikeTitle(String title) {
        return articleDao.findByTitleLike("%" + title + "%");
    }

}
